<?php
namespace app\api\controller\mytool;
use think\facade\Cache;
use app\common\model\user\User;
use app\api\controller\Base;

class Mpwechat extends Base
{
    public function index()
    {
		 return 'hello,' ;
	}
    /**
     * 获取小程序的token
     * @return [type] [description]
     */
    public static function getaccesstoken(){
        $data = Cache::get('Mpwechat_TOKEN');
        if($data!==false){
            return ['code'=>true,'msg'=>$data];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".MPWXAPPID."&secret=".MPWXSERCRET;
        $data = selfapi($url);
        if(empty($data['access_token'])){
            return ['code'=>false,'msg'=>'access_token获取失败']; 
        }else {
            Cache::set('Mpwechat_TOKEN',$data['access_token'],$data['expires_in']);
            return ['code'=>true,'msg'=>$data['access_token']];
        }
    }

    public static function geturl(){
        $str = empty(input('url'))?'type=1':'type='.input('url');
        $token = self::getaccesstoken();
        if(!$token['code']){
            return $token;
        }
        $url="https://api.weixin.qq.com/wxa/generatescheme?access_token=".$token['msg'];
        $data['jump_wxa'] = ['path'=>'pages/public/wxfollow','query'=>$str];
        $data = selfapi($url,$data);
        if($data['errmsg']=='ok'){
            // echo "正在跳转";
            // $data['openlink']="http://baidu.com";
            echo '<!DOCTYPE html><html><head><title>正在跳转</title></head><body>正在跳转<script>location.href="'.$data['openlink'].'"</script></body></html>';
        }else{
            echo "跳转失败";
            dump($data);
        }
    }

    /**
	 * 微信授权后请求用户信息，并登录系统获取jwt
	 */
	public function login(){
		try {
			$code = input('code');
			if (empty($code)) {
				return myerr("请重新登录");
			}
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".MPWXAPPID."&secret=".MPWXSERCRET."&js_code=".$code."&grant_type=authorization_code";
			$data = selfapi($url);
			if(empty($data['openid'])){
				return myerr();
			}
			$openid = $data['openid'];
			$session_key = $data['session_key'];

            //判断是否存在此微信id
            $data = User::ismpwechatid($openid);
            $user_id = '';
            if ($data['code']) {
                //找到微信openid
                $user_id = $data['msg'];
            }else{
                //没有找到账号-》创建账号
                $adduserdata = User::mp_wechat_adduser($openid);
                $user_id = $adduserdata['msg'];
            }
            $sb = User::user_login_state($user_id);
            if($sb['code']){
                $sb = Pub::getjwtkeyarray($user_id);
                if(!$sb['code']){
                    return myerr($sb['msg']);
                }
                $user  = User::get($user_id);
                $options =  empty(!$user ['Iphone'])?'':'register';     
                return myok(['token'=>$sb['msg'],'name'=>$user->Name],'',$options);
            }else{
                return myerr($sb['msg']);
            }
            return myok(['token'=>$sb['msg'],'name'=>$user->Name],'',$options);

		} catch (Exception $e) {
			return myerr("请重新登录");
		}
	}

	/**
    * 数据解密：低版本使用mcrypt库（PHP < 5.3.0），高版本使用openssl库（PHP >= 5.3.0）。
    *
    * @param string $ciphertext    待解密数据，返回的内容中的data字段
    * @param string $iv            加密向量，返回的内容中的iv字段
    * @param string $app_key       创建小程序时生成的app_key
    * @param string $session_key   登录的code换得的
    * @return string | false
    */
    private function decrypt($ciphertext, $iv, $app_key, $session_key) {
        $session_key = base64_decode($session_key);
        $iv = base64_decode($iv);
        $ciphertext = base64_decode($ciphertext);

        $plaintext = false;
        if (function_exists("openssl_decrypt")) {
            $plaintext = openssl_decrypt($ciphertext, "AES-192-CBC", $session_key, OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING, $iv);
        } else {
            $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, null, MCRYPT_MODE_CBC, null);
            mcrypt_generic_init($td, $session_key, $iv);
            $plaintext = mdecrypt_generic($td, $ciphertext);
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);
        }
        if ($plaintext == false) {
            return false;
        }

        // trim pkcs#7 padding
        $pad = ord(substr($plaintext, -1));
        $pad = ($pad < 1 || $pad > 32) ? 0 : $pad;
        $plaintext = substr($plaintext, 0, strlen($plaintext) - $pad);

        // trim header
        $plaintext = substr($plaintext, 16);
        // get content length
        $unpack = unpack("Nlen/", substr($plaintext, 0, 4));
        // get content
        $content = substr($plaintext, 4, $unpack['len']);
        // get app_key
        $app_key_decode = substr($plaintext, $unpack['len'] + 4);

        return $app_key == $app_key_decode ? $content : false;
    }
}
